//
//  HomeControlRuleView.swift
//  WatermarkCamera
//
//  Created by Python on 2024/7/24.
//

import UIKit
import AxcBedrock

class HomeControlRuleView: BaseView {

    /// 多少个单位
    let numOfUnits: Int
    /// 每个单位多少刻度
    let scalesOfUnit: Int
    
    /// 所有单位对应的刻度
    var unitValues: [CGFloat] = [] {
        didSet {
            setNeedsDisplay()
        }
    }
    
    var cursorLineW: CGFloat = 4.0 {
        didSet {
            updateCursor()
        }
    }

    /// 刻度值
    var value: CGFloat = 0.0 {
        didSet {
           updateCursor()
        }
    }

    private var justCursorUpdated: Bool = false
    
    init(numOfUnits: Int, scalesOfUnit: Int) {
        self.numOfUnits = numOfUnits
        self.scalesOfUnit = scalesOfUnit
        super.init(frame: .zero)
    }
    
    public required convenience init() {
        self.init(numOfUnits: 2, scalesOfUnit: 5)
    }
    
    
    override func createUI() {
        super.createUI()
        backgroundColor = UIColor.clear
    }

    override func draw(_ rect: CGRect) {
        guard numOfUnits > 0,
              scalesOfUnit > 0 else { return }
        // 宽高
        let width = rect.size.width
        let height = rect.size.height
        // 画刻度
        if !justCursorUpdated {
            drawRuleScales(width: width, height: height)
        }
        // 画指针
        drawCursor(width: width, height: height)
    }
}

extension HomeControlRuleView {
    
    private func calculateCursorHeight(width: CGFloat, height: CGFloat) -> CGFloat {
        guard let minValue = unitValues.first,
              let maxValue = unitValues.last else { return 0.0 }
        let _value = min(max(minValue, value), maxValue)
        var values = unitValues
        values.append(_value)
        values.sort()
        guard let index = values.firstIndex(of: _value) else { return 0.0 }
        let totalHeight: CGFloat
        if index == 0 {
            totalHeight = 0.0
        } else {
            let preValue = values[index - 1]
            let nextValue = values[index + 1]
            // 计算包裹当前刻度值的两个单位刻度值之间的差值
            let scaleInterval = nextValue - preValue
            // 计算当前刻度值与(距离最近并小于等于当前值的刻度值)之间的差值
            let valueInterval = _value - preValue
            // 计算所占比例
            let ratio = valueInterval / scaleInterval
            // 每个单位刻度的高度
            let unitHeight = height / CGFloat(numOfUnits)
            // 超出前面的刻度的一部分的高度
            let ratioHeight = unitHeight * ratio
            // 剩余的整数个单位刻度的高度
            let unitsNum = index - 1
            let unitsHeight = CGFloat(unitsNum) * unitHeight
            //
            totalHeight = ratioHeight + unitsHeight
        }
        return totalHeight
    }
    
    private func updateCursor() {
        justCursorUpdated = true
        setNeedsDisplay()
        justCursorUpdated = false
    }
    
    private func drawRuleScales(width: CGFloat, height: CGFloat) {
        // 总共多少个刻度
        let numOfScales = numOfUnits * scalesOfUnit
        // 总共多少条刻度线
        let numOfLines = numOfScales + 1
        // 线宽
        let lineW = 2.0
        // 每个刻度的高度
        let scaleHeight = (height - CGFloat(numOfLines) * lineW) / CGFloat(numOfScales)
        // 画线
        for index in 0..<numOfLines {
            let startX: CGFloat
            if index % scalesOfUnit == 0 {
                UIColor.white.setStroke()
                startX = 0.0
            } else {
                UIColor.white.withAlphaComponent(0.7).setStroke()
                startX = width * CGFloat(0.4)
            }
            // 第一条线总是缺少线宽的一半，所以Y值要加上线宽的一半才能完全显示
            let startY = CGFloat(index) * (scaleHeight + lineW) + lineW * 0.5
            let endX = width
            let endY = startY
            
            let startPoint = CGPoint(x: startX, y: startY)
            let endPoint = CGPoint(x: endX, y: endY)
            // 画线
            let path = UIBezierPath()
            path.lineWidth = lineW
            path.move(to: startPoint)
            path.addLine(to: endPoint)
            path.stroke()
        }
    }
    
    private func drawCursor(width: CGFloat, height: CGFloat) {
        let cursorPath = UIBezierPath()
        let cursorHeight = calculateCursorHeight(width: width, height: height)
        var cursorY = height - cursorHeight
        cursorY = max(cursorY, cursorLineW * 0.5)
        cursorY = min(cursorY, height - cursorLineW * 0.5)
        let startPoint = CGPoint(x: 0.0, y: cursorY)
        let endPoint = CGPoint(x: width, y: cursorY)
        cursorPath.move(to: startPoint)
        cursorPath.addLine(to: endPoint)
        cursorPath.lineWidth = cursorLineW
//        UIColor.yellowFF9305.setStroke()
        UIColor.Axc.Create(hexStr: "FF9305").setStroke()
        
        cursorPath.stroke()
    }
    
}
